/**
 * 多AI观点生成服务
 * 支持并发调用多个AI模型生成不同视角的观点
 */

import { PerspectiveType, Viewpoint } from '@/types/brainstorm';
import { useBrainstormStore } from '@/stores/brainstorm.store';

interface ViewpointRequest {
  sessionId: string;
  questionAnswers: Record<string, string>;
  models: string[];
  perspectives: PerspectiveType[];
}

interface ViewpointGenerationConfig {
  model: string;
  perspective: PerspectiveType;
  prompt: string;
}

/**
 * 多AI观点生成服务类
 */
class MultiAIViewpointService {
  private baseUrl: string;
  private wsConnections: Map<string, WebSocket> = new Map();

  constructor() {
    // 使用相对路径，让Vite代理处理
    this.baseUrl = '';
  }

  /**
   * 生成多个AI观点（并发调用）
   */
  async generateViewpoints(request: ViewpointRequest): Promise<void> {
    const { sessionId, questionAnswers, models, perspectives } = request;

    console.log('🚀 [MultiAI] Starting viewpoint generation:', {
      sessionId,
      models,
      perspectives,
    });

    // 为每个模型-视角组合创建配置
    const configs: ViewpointGenerationConfig[] = [];
    models.forEach((model, index) => {
      const perspective = perspectives[index % perspectives.length];
      const prompt = this.buildViewpointPrompt(questionAnswers, perspective);
      configs.push({ model, perspective, prompt });
    });

    // 并发调用所有模型
    await Promise.allSettled(
      configs.map((config) => this.generateSingleViewpoint(sessionId, config))
    );

    console.log('✅ [MultiAI] All viewpoint generation initiated');
  }

  /**
   * 生成单个AI观点（WebSocket流式）
   */
  private async generateSingleViewpoint(
    sessionId: string,
    config: ViewpointGenerationConfig,
    existingViewpointId?: string
  ): Promise<void> {
    const { model, perspective, prompt } = config;
    const connectionKey = `${model}-${perspective}`;

    console.log(`📡 [MultiAI] Generating viewpoint for ${connectionKey}`);

    // 如果有已存在的观点ID，使用它；否则创建新的
    let viewpointId = existingViewpointId;

    if (!viewpointId) {
      // 初始化观点状态
      const initialViewpoint: Viewpoint = {
        id: `viewpoint-${Date.now()}-${connectionKey}`,
        model,
        perspective,
        coreViewpoint: '',
        arguments: [],
        scenario: '',
        expectedEffect: '',
        generating: true,
        completed: false,
        content: '',
        aiScore: 0,
        scoreDetails: {
          relevance: 0,
          novelty: 0,
          feasibility: 0,
          impact: 0,
        },
        createdAt: new Date().toISOString(),
      };

      viewpointId = initialViewpoint.id;
      useBrainstormStore.getState().addViewpoint(initialViewpoint);
    }

    try {
      // 使用HTTP SSE代替WebSocket（更简单且可靠）
      await this.streamViewpointSSE(sessionId, config, viewpointId);
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);
      console.error(`❌ [MultiAI] Failed to generate viewpoint for ${connectionKey}: ${errorMsg}`);
      useBrainstormStore.getState().updateViewpoint(viewpointId, {
        generating: false,
        completed: false,
        error: error instanceof Error ? error.message : 'Generation failed',
      });
    }
  }

  /**
   * 使用SSE流式生成观点
   */
  private async streamViewpointSSE(
    sessionId: string,
    config: ViewpointGenerationConfig,
    viewpointId: string
  ): Promise<void> {
    const { model, perspective, prompt } = config;

    console.log(`[SSE] 开始请求观点生成: viewpointId=${viewpointId}, model=${model}, perspective=${perspective}`);

    const url = `${this.baseUrl}/api/v1/brainstorm/viewpoints/stream`;
    const requestBody = {
      session_id: sessionId,
      model,
      perspective,
      prompt,
    };

    console.log(`[SSE] 请求URL: ${url}`);
    console.log(`[SSE] 请求体:`, requestBody);

    let response;
    try {
      response = await fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(requestBody),
      });
      console.log(`[SSE] HTTP响应状态: ${response.status}`);
    } catch (fetchError) {
      const errorMsg = fetchError instanceof Error ? fetchError.message : String(fetchError);
      console.error(`[SSE] Fetch请求失败: ${errorMsg}`);
      throw new Error(`Fetch failed: ${errorMsg}`);
    }

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`[SSE] HTTP错误: ${response.status} - ${errorText}`);
      throw new Error(`HTTP ${response.status}: ${response.statusText}`);
    }

    const reader = response.body?.getReader();
    const decoder = new TextDecoder();

    if (!reader) {
      console.error('[SSE] Response body不可读');
      throw new Error('Response body is not readable');
    }

    console.log('[SSE] 开始读取流式响应');
    let buffer = '';
    let chunkCount = 0;
    let streamCompleted = false;

    try {
      while (true) {
        let readResult;
        try {
          readResult = await reader.read();
        } catch (readError) {
          const errorMsg = readError instanceof Error ? readError.message : String(readError);
          console.error(`[SSE] Reader.read() 错误: ${errorMsg}`);
          throw new Error(`Stream read error: ${errorMsg}`);
        }

        if (!readResult) {
          console.error('[SSE] Reader.read() 返回 undefined');
          break;
        }

        const { done, value } = readResult;

        if (done) {
          console.log(`[SSE] 流结束，共接收 ${chunkCount} 个数据块`);
          break;
        }

        if (!value || !value.byteLength || value.byteLength === 0) {
          console.warn('[SSE] 收到空的 value，跳过');
          continue;
        }

        chunkCount++;
        try {
          const decoded = decoder.decode(value, { stream: true });
          buffer += decoded;
        } catch (decodeError) {
          const errorMsg = decodeError instanceof Error ? decodeError.message : String(decodeError);
          console.error(`[SSE] 解码错误: ${errorMsg}`);
          continue;
        }

        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (!line.trim() || !line.startsWith('data: ')) continue;

          const data = line.slice(6); // Remove 'data: ' prefix
          if (data === '[DONE]') {
            console.log(`✅ [MultiAI] Viewpoint ${viewpointId} completed`);
            streamCompleted = true;
            break;
          }

          try {
            const parsed = JSON.parse(data);
            console.log(`[SSE] 解析数据: type=${parsed.type}`, parsed);

            if (parsed.type === 'chunk') {
              // 更新流式内容
              useBrainstormStore.getState().updateViewpoint(viewpointId, {
                content: (useBrainstormStore.getState().currentSession?.viewpoints.find(v => v.id === viewpointId)?.content || '') + parsed.content,
              });
            } else if (parsed.type === 'complete') {
              // 完成生成，解析结构化数据
              console.log(`[SSE] 观点生成完成，解析结构化数据`, parsed.data);
              this.parseAndCompleteViewpoint(viewpointId, parsed.data);
            } else if (parsed.type === 'error') {
              console.error(`[SSE] 服务器返回错误: ${parsed.message}`);
              throw new Error(parsed.message || 'Generation error');
            }
          } catch (error) {
            const errorMsg = error instanceof Error ? error.message : String(error);
            console.error(`❌ [MultiAI] Failed to parse SSE data: ${errorMsg}, raw data: ${data.substring(0, 100)}`);
          }
        }

        // 如果收到 [DONE] 标记，退出主循环
        if (streamCompleted) {
          console.log('[SSE] 检测到流完成标记，退出读取循环');
          break;
        }
      }
    } finally {
      // 确保释放 reader
      try {
        reader.releaseLock();
        console.log('[SSE] Reader 已释放');
      } catch (e) {
        const errorMsg = e instanceof Error ? e.message : String(e);
        console.log(`[SSE] Reader 释放失败（可能已释放）: ${errorMsg}`);
      }
    }
  }

  /**
   * 解析并完成观点数据
   */
  private parseAndCompleteViewpoint(viewpointId: string, data: any): void {
    try {
      // 获取当前的观点以保留原始主题描述
      const currentViewpoint = useBrainstormStore.getState().currentSession?.viewpoints.find(
        v => v.id === viewpointId
      );

      const updates: Partial<Viewpoint> = {
        // 保留原始主题描述
        topicDescription: currentViewpoint?.topicDescription || currentViewpoint?.coreViewpoint,
        // 使用AI生成的简短核心观点，如果没有则从原始文本提取
        coreViewpoint: this.extractShortCoreViewpoint(data.core_viewpoint || currentViewpoint?.coreViewpoint || ''),
        arguments: data.arguments || [],
        scenario: data.scenario || '',
        expectedEffect: data.expected_effect || '',
        aiScore: data.ai_score || 0,
        scoreDetails: data.score_details || {
          relevance: 0,
          novelty: 0,
          feasibility: 0,
          impact: 0,
        },
        scoreReason: data.score_reason,
        generating: false,
        completed: true,
      };

      useBrainstormStore.getState().updateViewpoint(viewpointId, updates);
      console.log(`✅ [MultiAI] Viewpoint ${viewpointId} parsed and completed`);
    } catch (error) {
      const errorMsg = error instanceof Error ? error.message : String(error);
      console.error(`❌ [MultiAI] Failed to parse viewpoint data: ${errorMsg}`);
      useBrainstormStore.getState().updateViewpoint(viewpointId, {
        generating: false,
        completed: false,
        error: 'Failed to parse viewpoint data',
      });
    }
  }

  /**
   * 从长文本中提取简短的核心观点
   */
  private extractShortCoreViewpoint(text: string): string {
    if (!text) return '';

    // 如果文本已经很短，直接返回
    if (text.length <= 50) {
      return text;
    }

    // 提取第一个句子作为核心观点
    const firstSentence = text.split(/[。！？]/)[0];
    if (firstSentence && firstSentence.length <= 50) {
      return firstSentence;
    }

    // 如果第一个句子还是太长，提取前30个字符
    return text.substring(0, 30) + '...';
  }

  /**
   * 重新生成单个观点
   */
  async regenerateViewpoint(viewpointId: string): Promise<void> {
    const store = useBrainstormStore.getState();
    const viewpoint = store.currentSession?.viewpoints.find((v) => v.id === viewpointId);

    if (!viewpoint || !store.currentSession) {
      throw new Error('Viewpoint or session not found');
    }

    // 重置观点状态
    store.updateViewpoint(viewpointId, {
      generating: true,
      completed: false,
      error: undefined,
      content: '',
      coreViewpoint: '',
      arguments: [],
      scenario: '',
      expectedEffect: '',
    });

    // 重新生成 - 传递已有的 viewpoint ID
    const questionAnswers = this.extractQuestionAnswers(store.currentSession.questions);
    const config: ViewpointGenerationConfig = {
      model: viewpoint.model,
      perspective: viewpoint.perspective,
      prompt: this.buildViewpointPrompt(questionAnswers, viewpoint.perspective),
    };

    await this.generateSingleViewpoint(store.currentSession.id, config, viewpointId);
  }

  /**
   * 构建观点生成Prompt
   */
  private buildViewpointPrompt(
    questionAnswers: Record<string, string>,
    perspective: PerspectiveType
  ): string {
    const perspectivePrompts: Record<PerspectiveType, string> = {
      rational: `你是一位理性分析专家。请基于以下问答内容，提供逻辑严谨、数据驱动、客观分析的观点。

要求：
- 核心观点要基于事实和逻辑推理
- 论据要具体、可验证
- 避免情感化表达，注重客观分析
- 适合学术、专业领域的读者

请以JSON格式返回：
{
  "core_viewpoint": "核心观点（1-2句话）",
  "arguments": ["论据1", "论据2", "论据3"],
  "scenario": "适用场景",
  "expected_effect": "预期效果",
  "ai_score": 85,
  "score_details": {
    "relevance": 90,
    "novelty": 75,
    "feasibility": 85,
    "impact": 80
  },
  "score_reason": "评分理由"
}`,
      emotional: `你是一位情感表达专家。请基于以下问答内容，提供富有感染力、故事化、人性化的观点。

要求：
- 核心观点要能引起情感共鸣
- 论据要结合真实故事或案例
- 使用生动的语言和比喻
- 适合大众读者，容易产生共鸣

请以JSON格式返回：
{
  "core_viewpoint": "核心观点（1-2句话）",
  "arguments": ["论据1（结合故事）", "论据2", "论据3"],
  "scenario": "适用场景",
  "expected_effect": "预期情感效果",
  "ai_score": 85,
  "score_details": {
    "relevance": 90,
    "novelty": 75,
    "feasibility": 85,
    "impact": 80
  },
  "score_reason": "评分理由"
}`,
      innovative: `你是一位创新思维专家。请基于以下问答内容，提供独特、颠覆性、跨界联想的观点。

要求：
- 核心观点要有新颖性，打破常规思维
- 论据可以跨界借鉴不同领域
- 鼓励大胆假设和创新想法
- 适合探索新方向、寻求突破的场景

请以JSON格式返回：
{
  "core_viewpoint": "创新观点（1-2句话）",
  "arguments": ["创新论据1", "论据2", "论据3"],
  "scenario": "适用场景",
  "expected_effect": "预期创新效果",
  "ai_score": 85,
  "score_details": {
    "relevance": 90,
    "novelty": 95,
    "feasibility": 75,
    "impact": 85
  },
  "score_reason": "评分理由"
}`,
      popular: `你是一位大众传播专家。请基于以下问答内容，提供通俗易懂、贴近生活、实用导向的观点。

要求：
- 核心观点要简单明了，一听就懂
- 论据要贴近日常生活，有实用价值
- 避免专业术语，使用大白话
- 适合普通大众读者

请以JSON格式返回：
{
  "core_viewpoint": "通俗观点（1-2句话）",
  "arguments": ["实用论据1", "论据2", "论据3"],
  "scenario": "日常应用场景",
  "expected_effect": "实用效果",
  "ai_score": 85,
  "score_details": {
    "relevance": 90,
    "novelty": 70,
    "feasibility": 95,
    "impact": 80
  },
  "score_reason": "评分理由"
}`,
    };

    const qaText = Object.entries(questionAnswers)
      .map(([question, answer]) => `**问题**: ${question}\n**回答**: ${answer}`)
      .join('\n\n');

    return `${perspectivePrompts[perspective]}

---

## 问答内容

${qaText}

---

请基于以上问答，生成${this.getPerspectiveName(perspective)}的观点建议。`;
  }

  /**
   * 获取视角名称
   */
  private getPerspectiveName(perspective: PerspectiveType): string {
    const names: Record<PerspectiveType, string> = {
      rational: '理性分析',
      emotional: '情感共鸣',
      innovative: '创新思维',
      popular: '大众实用',
    };
    return names[perspective];
  }

  /**
   * 从问题列表提取问答对
   */
  private extractQuestionAnswers(questions: any[]): Record<string, string> {
    const qa: Record<string, string> = {};
    questions.forEach((q) => {
      if (q.answer && !q.skipped) {
        qa[q.text] = q.answer;
      }
    });
    return qa;
  }

  /**
   * 批量生成观点（快捷方法）
   */
  async generateAllPerspectives(
    sessionId: string,
    models: string[] = ['gpt-4', 'claude', 'deepseek', 'qwen']
  ): Promise<void> {
    const store = useBrainstormStore.getState();
    const session = store.currentSession;

    if (!session) {
      throw new Error('No active session');
    }

    const questionAnswers = this.extractQuestionAnswers(session.questions);
    const perspectives: PerspectiveType[] = ['rational', 'emotional', 'innovative', 'popular'];

    await this.generateViewpoints({
      sessionId,
      questionAnswers,
      models,
      perspectives,
    });
  }

  /**
   * 清理WebSocket连接
   */
  cleanup(): void {
    this.wsConnections.forEach((ws) => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.close();
      }
    });
    this.wsConnections.clear();
  }
}

export const multiAIViewpointService = new MultiAIViewpointService();
